MODULE get_unitmod
!
! This returns the number of an unused file unit
!
! It tries unit numbers from 100 upwards and returns the first free unit.
! It aborts if it runs out of valid unit numbers.
!
  CONTAINS

    INTEGER FUNCTION get_unit()

      IMPLICIT NONE
      INTEGER :: i
      LOGICAL :: open, exists

      i = 100
      open   = .TRUE.
      exists = .TRUE.
      DO WHILE(open.AND.exists)
         i=i+1
         INQUIRE(UNIT=i,OPENED=open,EXIST=exists)
      END DO

      IF(.NOT.exists)THEN
         WRITE(*,*)'Error in get_unit(): ran out of valid unit numbers!'
         STOP
      END IF

      get_unit = i
      
      RETURN
    END FUNCTION get_unit

END MODULE get_unitmod
